package cn.jiedh.app.meiweidk.welcome;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;

import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.jiedh.app.meiweidk.MainActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.DeviceUtils;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.RSAUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StartupUtils;
import cn.jiedh.app.meiweidk.Utils.tool.StatusBarUtil;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.app.EnvConfig;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.buried.BuriedIntentService;
import cn.jiedh.app.meiweidk.entity.ApplicationPageBean;
import cn.jiedh.app.meiweidk.login.LoginActivity;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsManager;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsResultAction;

/**
 * @name：
 * @author： 周毅
 * @phone： 15826080712
 * @createTime： 2017/10/26
 * @modifyTime： 2017/10/26
 * @explain：
 */

public class WelcomeActivity extends BaseActivity {
    @BindView(R.id.wec_img)
    ImageView wecImg;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Intent intent = getIntent();
            if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                SPUtils.clearH5();
                Uri uri = intent.getData();
                if (uri != null) {
                    String page = uri.getQueryParameter("page");
                    String pid = uri.getQueryParameter("pid");
                    String rid = uri.getQueryParameter("rid");
                    SPUtils.saveToApp(activity, ConfigUtils.PAGE, page);
                    SPUtils.saveToApp(activity, ConfigUtils.PID, pid);
                    SPUtils.saveToApp(activity, ConfigUtils.RID, rid);
                }


                Bundle bundle = new Bundle();
                bundle.putInt("page", 2);

                if (SPUtils.getIsLogin()) {
                    ActivityUtil.next(activity, MainActivity.class, bundle);
                } else {
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(activity, LoginActivity.class, bundle);

                }


            } else if (Intent.ACTION_MAIN.equals(intent.getAction())) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                date();
            }
            finish();
        }
    };

    @Override
    protected int getLayoutView() {
        return R.layout.welcome;
    }

    @Override
    protected void initView(View view) {
        StatusBarUtil.transparencyBar(this);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.3f, 1.0f);
        alphaAnimation.setDuration(1000);
        wecImg.startAnimation(alphaAnimation);
        handler.postDelayed(runnable, 1000);
        boolean applicationPage = (boolean) SPUtils.getFromApp(this, "applicationPage", false);
        L.i("applicationPage", applicationPage + "");
//        UrlUtils.appKey = AuditConstant.releaseAppKey;
//        RSAUtils.PRIVATE_KEY = AuditConstant.releasePrivate_Key;
//        RSAUtils.PUBLIC_KEY = AuditConstant.releasePublic_Key;
        RSAUtils.APP_KEY = EnvConfig.APP_KEY;
        RSAUtils.PRIVATE_KEY = EnvConfig.PRIVATE_KEY;
        RSAUtils.PUBLIC_KEY = EnvConfig.PUBLIC_KEY;
//        if (!applicationPage) {
//        }

//        //登录状态时请求
//        if (SPUtils.getIsLogin()) {
        //页面切换请求
        getApplicationPage();
//        }
        //广告请求
        getadver();
        //贷款金额及用途请求
        getmoneyandyontu();

    }


    private void getmoneyandyontu() {
        Map<String, Object> map = new HashMap<>();
        request(activity, UrlUtils.MONEYANDYONGTU, map, true, new ResponseSuccess<MoneyAndYTData>() {
            @Override
            public void onRequestSucceed(BaseResponse<MoneyAndYTData> response) {
                if (response.getCode() == 0) {
                    if (response.getData() != null) {
                        SPUtils.putMoneyandYongtu(response.getData());
                    }
                }
            }
        });
    }

    private void getApplicationPage() {
        Map<String, Object> map = new HashMap<>();
        request(this, UrlUtils.APPLICATIONPAGE, map, false, new ResponseSuccess<ApplicationPageBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<ApplicationPageBean> response) {

                L.i("版面：", "page = " + response.getData().getPage() + "");
                if ("0".equals(response.getData().getPage())) { //正式页面
                    RSAUtils.APP_KEY = EnvConfig.APP_KEY;
                    RSAUtils.PRIVATE_KEY = EnvConfig.PRIVATE_KEY;
                    RSAUtils.PUBLIC_KEY = EnvConfig.PUBLIC_KEY;
//                    SPUtils.saveToApp(WelcomeActivity.this, "applicationPage", true);
                } else {//审核页面
                    RSAUtils.APP_KEY = EnvConfig.AUDIT_APPKEY;
                    RSAUtils.PRIVATE_KEY = EnvConfig.AUDIT_PRIVATE_KEY;
                    RSAUtils.PUBLIC_KEY = EnvConfig.AUDIT_PUBLIC_KEY;
//                    SPUtils.saveToApp(WelcomeActivity.this, "applicationPage", false);
                }

            }


        });
    }

    @Override
    protected void initData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, new String[]{android.Manifest.permission.READ_PHONE_STATE}, new PermissionsResultAction() {
                @Override
                public void onGranted() {
                    Intent intent = new Intent(WelcomeActivity.this, BuriedIntentService.class);
                    intent.putExtra("mobilePhone", SPUtils.getPhone());
                    startService(intent);
                }

                @Override
                public void onDenied(String permission) {

                }
            });
        } else {
            Intent intent = new Intent(WelcomeActivity.this, BuriedIntentService.class);
            intent.putExtra("mobilePhone", SPUtils.getPhone());
            startService(intent);
        }
    }

    private boolean openADdver = false;//是否打开广告页 默认为不打开

    public void getadver() {
        request(activity, UrlUtils.ADVER, new HashMap<String, Object>(), false, new ResponseSuccess<AdverBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<AdverBean> response) {
                if (response.getCode() == 0) {
                    AdverBean adverBean = response.getData();
                    SPUtils.putAdver(adverBean);
                    openADdver = true;
                } else {
                    openADdver = false;
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {

            }
        });
    }


    public void date() {
        String lastVersion = SPUtils.getLastVersion(activity);
        String currentVersion = DeviceUtils.getversionName(activity);
        if (!currentVersion.equals(lastVersion)) {
            //第一次进入跳转
            Intent in = new Intent(activity, YinDaoAcitivity.class);
            activity.startActivity(in);
            activity.finish();
            SPUtils.setLastVersion(activity, currentVersion);
            L.d("版本号更新或第一次使用APP 进入引导页");
        } else {
            //第二次进入跳转
            if (SPUtils.getadver() != null) {
                if (SPUtils.getadver().getLink() != null && openADdver) {
                    ActivityUtil.next(activity, GuangGaoActivity.class);
                } else {
                    //应该是在这里改逻辑 应该是这样吧
                    if (SPUtils.getIsLogin()) {
                        ActivityUtil.next(activity, MainActivity.class);
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGoHome", true);
                        ActivityUtil.next(activity, LoginActivity.class, bundle);

                    }
                }
            } else {
                //应该是在这里改逻辑 应该是这样吧
                if (SPUtils.getIsLogin()) {
                    ActivityUtil.next(activity, MainActivity.class);
                } else {

                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome", true);
                    ActivityUtil.next(activity, LoginActivity.class, bundle);

                }
            }

            activity.finish();
            L.d("版本号未更新或不是第一次使用APP 进入GuangGaoActivity或MainActivity");

        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
